package developer.zyk.starter.controllers.chat.vo;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import developer.zyk.ability.chat.dao.entity.ChatHistoryDO;
import developer.zyk.ability.chat.dao.entity.ChatHistoryDetailDO;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Data
public class ChatDetailVO implements Serializable {
    private Long chatId;
    private String title;
    private List<Message> messages;

    @Data
    public static class Message {
        private Long chatDetailId;
        private String role;
        private String messageJson;
        private JSONObject msgObj;
        private Integer chatOrder;
    }


    public static ChatDetailVO of(ChatHistoryDO chatHistoryDO, List<ChatHistoryDetailDO> chatHistoryDetailDOS) {
        ChatDetailVO chatDetailVO = new ChatDetailVO();
        chatDetailVO.setChatId(chatHistoryDO.getId());
        chatDetailVO.setTitle(chatHistoryDO.getTitle());

        List<Message> datas = Optional.ofNullable(chatHistoryDetailDOS).orElse(new ArrayList<>())
                .stream()
                .map(a -> {
                    Message message = new Message();
                    message.setChatDetailId(a.getId());
                    message.setRole(a.getChatRole());
                    message.setMessageJson(a.getSendMessage());
                    message.setMsgObj(JSONUtil.parseObj(a.getSendMessage()));
                    message.setChatOrder(a.getChatOrder());
                    return message;
                }).toList();
        chatDetailVO.setMessages(datas);
        return chatDetailVO;
    }
}
